posmax: like argmax but gives the position(s) of the element x for which f[x] is maximal
Posted
by dreeves
on Stack Overflow
See other posts from Stack Overflow
or by dreeves
Published on 2010-04-17T00:35:47Z
Indexed on
2010/04/17
0:43 UTC
Read the original article
Hit count: 320
Mathematica has a built-in function ArgMax for functions over infinite domains, based on the standard mathematical definition.
The analog for finite domains is a handy utility function. Given a function and a list (call it the domain of the function), return the element(s) of the list that maximize the function. Here's an example of finite argmax in action: http://stackoverflow.com/questions/471029/canonicalize-nfl-team-names/472213#472213
And here's my implementation of it (along with argmin for good measure):
(* argmax[f, domain] returns the element of domain for which f of
that element is maximal -- breaks ties in favor of first occurrence. *)
SetAttributes[{argmax, argmin}, HoldFirst];
argmax[f_, dom_List] := Fold[If[f[#1]>=f[#2], #1, #2]&, First[dom], Rest[dom]]
argmin[f_, dom_List] := argmax[-f[#]&, dom]
First, is that the most efficient way to implement argmax? What if you want the list of all maximal elements instead of just the first one?
Second, how about the related function posmax that, instead of returning the maximal element(s), returns the position(s) of the maximal elements?
© Stack Overflow or respective owner